﻿// (c) Copyright Damian Mehers http://damianblog.com/
// This source is subject to the Microsoft Public License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx.
// All other rights reserved.

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;

namespace MceFM.Last {
  class ID3TagManager {
    bool addPicture = true;

    Track track;
    ID3Lib.TagModel tagModel = new ID3Lib.TagModel();

    public ID3TagManager(Track track, bool addPicture) {
      this.track = track;
      this.addPicture = addPicture;
    }

    public void AddTags(string title, string creator, string album)
    {
      AddTextFrame("TIT2", title);
      AddTextFrame("TPE1", creator);
      AddTextFrame("TALB", album);
    }


    public void AddTags() {
      AddTextFrame("TIT2", track.Title);
      AddTextFrame("TPE1", track.Creator);
      AddTextFrame("TALB", track.Album);

      AddPictureFrame();
    }

    public byte[] GetBuffer() {
      ID3Lib.TagManager tagManager = new ID3Lib.TagManager();
      System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
      tagManager.Serialize(tagModel, memoryStream);
      return memoryStream.ToArray();
    }


    private void AddTextFrame(string frameName, string content) {
      ID3Lib.FrameText frame = new ID3Lib.FrameText(frameName);
      frame.Text = content;
      tagModel.Frames.Add(frame);
    }

    private void AddPictureFrame() {
      if(!addPicture || string.IsNullOrEmpty(track.Image)) {
        Trace.WriteLine("Not Getting picture: " + track.Image);
        return;
      }

      if(track.ImageData != null && track.ImageData.Length != 0) {
        ID3Lib.FrameAPIC picture = new ID3Lib.FrameAPIC();
        picture.PictureData = track.ImageData;
        picture.Mime = track.ImageDataType;
        tagModel.Frames.Add(picture);
      }

    }


  }
}
